import 'dart:io';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:xcite/core/utils/ali.dart';

import '../../core/services/intelligent_chat_service.dart';
import '../../core/providers/user_provider.dart';
import '../../core/utils/toast_helper.dart';
import '../../core/utils/popup_helper.dart';

class IntelligentChatScreen extends ConsumerStatefulWidget {
  const IntelligentChatScreen({super.key});

  @override
  ConsumerState<IntelligentChatScreen> createState() =>
      _IntelligentChatScreenState();
}

class _IntelligentChatScreenState extends ConsumerState<IntelligentChatScreen> {
  final IntelligentChatService _chatService = IntelligentChatService();
  final TextEditingController _messageController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  final List<ChatMessageModel> _conversationMessages = [];

  bool _isProcessingMessage = false;
  bool _isInitialState = true;
  File? _selectedImage;

  @override
  void dispose() {
    _messageController.dispose();
    _scrollController.dispose();
    _chatService.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/common_bg_2.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child:
              [
                _buildTopNavigationBar(),

                Expanded(
                  child:
                      _isInitialState
                          ? _buildWelcomeMessage()
                          : _buildConversationArea(),
                ),

                _buildInputArea(),
              ].toColumn(),
        ),
      ),
    );
  }

  Widget _buildTopNavigationBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h),
      child:
          [
            Container(
              width: 30.w,
              height: 30.w,
              decoration: BoxDecoration(
                color: Colors.black,
                shape: BoxShape.circle,
              ),
              child:
                  Icon(
                    Icons.arrow_back_ios,
                  ).iconSize(20.sp).iconColor(Colors.white).center(),
            ).inkWell(onTap: () => GoRouter.of(context).pop()),

            Spacer(),

            Text(
              'AI Recognition',
              style: TextStyle(
                fontSize: 24.sp,
                color: Colors.black,
                fontWeight: FontWeight.bold,
                fontFamily: 'PoetsenOne',
              ),
            ),

            Spacer(),

            Container(
              width: 30.w,
              height: 30.w,
              decoration: BoxDecoration(
                color: Colors.black,
                shape: BoxShape.circle,
              ),
              child:
                  Icon(
                    AliIcons.iconReport,
                  ).iconSize(22.sp).iconColor(Colors.white).center(),
            ).inkWell(onTap: _showReportDialog),
          ].toRow(),
    );
  }

  Widget _buildWelcomeMessage() {
    return Container(
      padding: EdgeInsets.all(24.w),
      child:
          [
            SizedBox(height: 60.h),

            Container(
              width: double.infinity,
              height: 120.h,
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/resources/kid.png'),
                  fit: BoxFit.contain,
                ),
              ),
            ),

            Text(
              'Hello! I\'m your AI Assistant',
              style: TextStyle(
                fontSize: 24.sp,
                fontWeight: FontWeight.bold,
                color: Colors.white,
              ),
              textAlign: TextAlign.center,
            ),

            SizedBox(height: 12.h),

            Text(
              'Tip:Use AI to identify flowers during a spring outing.',
              style: TextStyle(
                fontSize: 14.sp,
                color: Colors.white,
                height: 1.4,
              ),
              textAlign: TextAlign.center,
            ),
          ].toColumn().center(),
    );
  }

  Widget _buildConversationArea() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: ListView.builder(
        controller: _scrollController,
        padding: EdgeInsets.symmetric(vertical: 16.h),
        itemCount: _conversationMessages.length,
        itemBuilder: (context, index) {
          final message = _conversationMessages[index];
          return _buildMessageBubble(message);
        },
      ),
    );
  }

  Widget _buildMessageBubble(ChatMessageModel message) {
    final isUserMessage = message.isFromUser;
    final currentUser = ref.watch(currentUserProvider);

    return Container(
      margin: EdgeInsets.only(bottom: 16.h),
      child: [
        if (!isUserMessage) ...[
          _buildUserAvatar(false, currentUser),
          SizedBox(width: 12.w),
          Expanded(
            child: [
              _buildMessageContent(message, isUserMessage),
            ].toColumn(crossAxisAlignment: CrossAxisAlignment.start),
          ),
          SizedBox(width: 40.w),
        ] else ...[
          SizedBox(width: 40.w),
          Expanded(
            child: [
              _buildMessageContent(message, isUserMessage),
            ].toColumn(crossAxisAlignment: CrossAxisAlignment.end),
          ),
          SizedBox(width: 12.w),
          _buildUserAvatar(true, currentUser),
        ],
      ].toRow(crossAxisAlignment: CrossAxisAlignment.start),
    );
  }

  Widget _buildUserAvatar(bool isCurrentUser, dynamic currentUser) {
    if (isCurrentUser) {
      if (currentUser == null) {
        return Container(
          width: 52.w,
          height: 52.w,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            color: Colors.grey.shade300,
          ),
          child:
              Icon(
                Icons.person,
                size: 28.sp,
                color: Colors.grey.shade600,
              ).center(),
        );
      } else if (currentUser.avatar.isNotEmpty) {
        return Container(
          width: 52.w,
          height: 52.w,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            image: DecorationImage(
              image: NetworkImage(currentUser.avatar),
              fit: BoxFit.cover,
            ),
          ),
        );
      } else {
        return Container(
          width: 52.w,
          height: 52.w,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            color: Colors.grey.shade300,
          ),
          child:
              Icon(
                Icons.person,
                size: 28.sp,
                color: Colors.grey.shade600,
              ).center(),
        );
      }
    } else {
      return Container(
        width: 52.w,
        height: 52.w,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          image: DecorationImage(
            image: AssetImage('assets/resources/kid.png'),
            fit: BoxFit.cover,
          ),
        ),
      );
    }
  }

  Widget _buildMessageContent(ChatMessageModel message, bool isUserMessage) {
    return [
      if (message.imagePath != null) ...[
        _buildImageBubble(message.imagePath!, isUserMessage),
        SizedBox(height: 8.h),
      ],

      if (message.content.isNotEmpty && message.content != 'Sent an image') ...[
        _buildTextBubble(message.content, isUserMessage),
        SizedBox(height: 4.h),
      ],

      Text(
        _formatTimestamp(message.timestamp),
        style: TextStyle(fontSize: 12.sp, color: Colors.white),
      ),
    ].toColumn(
      crossAxisAlignment:
          isUserMessage ? CrossAxisAlignment.end : CrossAxisAlignment.start,
    );
  }

  Widget _buildTextBubble(String content, bool isUserMessage) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.black,
        borderRadius: BorderRadius.circular(29.r),
      ),
      padding:
          isUserMessage
              ? EdgeInsets.only(left: 2.w, bottom: 2.w)
              : EdgeInsets.only(right: 2.w, bottom: 2.w),
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
        decoration: BoxDecoration(
          color: Color(0xFFFDF5E1),
          borderRadius: BorderRadius.circular(29.r),
          border: Border.all(color: Colors.black, width: 2.w),
        ),
        child: Text(
          content,
          style: TextStyle(fontSize: 14.sp, color: Colors.black),
        ),
      ),
    );
  }

  Widget _buildImageBubble(String imagePath, bool isUserMessage) {
    return Container(
      width: 155.w,
      height: 155.w,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(color: Colors.black, width: 2.w),
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(10.r),
        child: Image.file(
          File(imagePath),
          fit: BoxFit.cover,
          errorBuilder: (context, error, stackTrace) {
            return Container(
              color: Colors.grey.shade300,
              child: Icon(Icons.broken_image, size: 40.sp).center(),
            );
          },
        ),
      ),
    );
  }

  Widget _buildInputArea() {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(color: Colors.transparent),
      child: SafeArea(
        child: Container(
          decoration: BoxDecoration(
            color: Colors.black,
            borderRadius: BorderRadius.circular(28.r),
          ),
          padding: EdgeInsets.only(right: 2.w, bottom: 2.w),
          child: Container(
            height: 56.h,
            padding: EdgeInsets.symmetric(horizontal: 16.w),
            decoration: BoxDecoration(
              color: Color(0xFFFDF5E1),
              borderRadius: BorderRadius.circular(28.r),
              border: Border.all(width: 2.w, color: Colors.black),
            ),
            child:
                [
                  Expanded(
                    child: TextField(
                      controller: _messageController,
                      maxLines: null,
                      textInputAction: TextInputAction.done,
                      style: TextStyle(fontSize: 16.sp),
                      decoration: InputDecoration(
                        border: InputBorder.none,
                        hintText:
                            _selectedImage != null
                                ? 'Add a message for image...'
                                : 'Type a message...',
                        hintStyle: TextStyle(
                          fontSize: 16.sp,
                          color: Colors.grey.shade500,
                        ),

                        hintMaxLines: 1,
                      ),
                      onSubmitted: (_) => _sendMessage(),
                    ),
                  ),

                  [
                    Container(
                      width: 46.w,
                      height: 46.w,
                      decoration: BoxDecoration(
                        color:
                            _selectedImage != null
                                ? Color(0xFFFDDB31).withValues(alpha: 0.7)
                                : Color(0xFFFDDB31),
                        shape: BoxShape.circle,
                      ),
                      child:
                          Icon(
                            AliIcons.iconPhoto,
                            size: 26.sp,
                            color:
                                _selectedImage != null
                                    ? Color(0xFF2AB061)
                                    : Colors.white,
                          ).center(),
                    ).inkWell(onTap: _selectImage),

                    SizedBox(width: 8.w),

                    Container(
                      width: 46.w,
                      height: 46.w,
                      decoration: BoxDecoration(
                        color:
                            _isProcessingMessage
                                ? Colors.grey.shade300
                                : Color(0xFFFDDB31),
                        shape: BoxShape.circle,
                      ),
                      child:
                          _isProcessingMessage
                              ? SizedBox(
                                width: 16.w,
                                height: 16.w,
                                child: CircularProgressIndicator(
                                  strokeWidth: 2,
                                  valueColor: AlwaysStoppedAnimation<Color>(
                                    Colors.white,
                                  ),
                                ),
                              ).center()
                              : Icon(
                                AliIcons.iconSend,
                                size: 22.sp,
                                color: Colors.white,
                              ).center(),
                    ).inkWell(
                      onTap: _isProcessingMessage ? null : _sendMessage,
                    ),
                  ].toRow(),
                ].toRow(),
          ),
        ),
      ),
    );
  }

  String _formatTimestamp(DateTime timestamp) {
    final now = DateTime.now();
    final difference = now.difference(timestamp);

    if (difference.inMinutes < 1) {
      return '${timestamp.hour.toString().padLeft(2, '0')}:${timestamp.minute.toString().padLeft(2, '0')}';
    } else if (difference.inHours < 1) {
      return '${difference.inMinutes}m ago';
    } else if (difference.inDays < 1) {
      return '${difference.inHours}h ago';
    } else {
      return '${timestamp.month}/${timestamp.day}';
    }
  }

  void _selectImage() async {
    try {
      final List<AssetEntity>? result = await AssetPicker.pickAssets(
        context,
        pickerConfig: AssetPickerConfig(
          maxAssets: 1,
          requestType: RequestType.image,
          themeColor: Color(0xFF2AB061),
          textDelegate: AssetPickerTextDelegate(),
        ),
      );

      if (result != null && result.isNotEmpty) {
        final AssetEntity asset = result.first;
        final File? imageFile = await asset.file;

        if (imageFile != null) {
          setState(() {
            _selectedImage = imageFile;
          });
        }
      }
    } catch (e) {
      if (mounted) {
        ToastHelper.error('Failed to select image', context: context);
      }
    }
  }

  void _showReportDialog() {
    PopupHelper.showReportDialog(
      context,
      onReportSubmitted: (reportType) {
        GoRouter.of(context).pop();
      },
    );
  }

  void _sendMessage() async {
    final messageText = _messageController.text.trim();
    final hasImage = _selectedImage != null;

    if (messageText.isEmpty && !hasImage) return;
    if (_isProcessingMessage) return;

    final currentUser = ref.read(currentUserProvider);

    final displayText =
        hasImage
            ? (messageText.isEmpty ? 'Sent an image' : messageText)
            : messageText;

    final userMessage = ChatMessageModel(
      messageId: DateTime.now().millisecondsSinceEpoch.toString(),
      content: displayText,
      isFromUser: true,
      timestamp: DateTime.now(),
      imagePath: _selectedImage?.path,
    );

    setState(() {
      _conversationMessages.add(userMessage);
      _isInitialState = false;
      _isProcessingMessage = true;
    });

    _messageController.clear();
    final imageToSend = _selectedImage;
    setState(() {
      _selectedImage = null;
    });

    _scrollToBottom();

    Map<String, dynamic> response;

    if (hasImage && imageToSend != null) {
      final promptText =
          messageText.isEmpty
              ? 'Please analyze this image and tell me what you see.'
              : messageText;

      response = await _chatService.sendImageWithTextMessage(
        userIdentifier: currentUser?.id ?? 'guest',
        imageFile: imageToSend,
        textMessage: promptText,
      );
    } else {
      final conversationHistory =
          _conversationMessages
              .where((msg) => msg.imagePath == null)
              .map(
                (msg) => {
                  'role': msg.isFromUser ? 'user' : 'assistant',
                  'content': msg.content,
                },
              )
              .toList();

      response = await _chatService.continueTextConversation(
        textMessage: messageText,
        conversationHistory: conversationHistory,
      );
    }

    if (mounted) {
      setState(() {
        _isProcessingMessage = false;
      });

      if (response['success']) {
        final aiMessage = ChatMessageModel(
          messageId: DateTime.now().millisecondsSinceEpoch.toString(),
          content: response['response'],
          isFromUser: false,
          timestamp: DateTime.now(),
        );

        setState(() {
          _conversationMessages.add(aiMessage);
        });

        _scrollToBottom();
      } else {
        ToastHelper.error('Failed to get AI response', context: context);
      }
    }
  }

  void _scrollToBottom() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_scrollController.hasClients) {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          duration: Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }
}
